/*
 * @Author: youzi 17639310612@163.com
 * @Date: 2023-12-16 16:02:47
 * @LastEditors: youzi 17639310612@163.com
 * @LastEditTime: 2024-02-02 16:21:46
 * @FilePath: \vue-houtai\src\router\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './index.js';
import { getToken } from '@/utils/token';
import { useUserStore } from '@/store/modules/user';
import permissionRoutes from './dynamicRoutes.js';
import { staticRoutes, notFoundRouter } from './constantRoutes.js';
import { ElNotification } from 'element-plus';

const ROUTER_WHITE_LIST = ['/login', '/404'];

router.beforeEach(async (to, from, next) => {
	const token = getToken();
	if (token) {
		if (to.path === '/login') {
			next({ path: '/' });
		} else {
			const useUser = useUserStore();
			if (!useUser.userInfo.hasOwnProperty('permission_list')) {
				ElNotification({
					title: '授权过期通知',
					message: '账号授权已过期,请点击头像使用卡密续费！',
					type: 'error',
					duration: 0,
				});
			}
			const filteredRoutes = filterRoutesByPermissions(permissionRoutes, useUser.userInfo.permission_list);
			for (const route of filteredRoutes) {
				if (!router.hasRoute(route.name)) {
					router.addRoute('LAYOUT', route);
				}
			}

			if (!router.hasRoute(notFoundRouter.name)) {
				router.addRoute(notFoundRouter);
			}

			const menuList = getMenuList([...staticRoutes, ...filteredRoutes]);
			useUser.setMenuList(menuList);

			if (!to.redirectedFrom) {
				next({ ...to, replace: true });
			} else {
				next();
			}
		}
	} else {
		if (ROUTER_WHITE_LIST.includes(to.path)) {
			next();
		} else {
			next({ path: '/login' });
		}
	}
});
/**
 * @description 路由过滤
 */
const filterRoutesByPermissions = (routes, permissions) => {
	return routes.filter((route) => {
		if (route.children && route.children.length > 0) {
			route.children = filterRoutesByPermissions(route.children, permissions);
			return route.children.length > 0;
		}
		if (permissions !== undefined) {
			return permissions.includes(route.meta.name);
		} else {
			return '';
		}
	});
};

/**
 * @description menu过滤
 */
const getMenuList = (menuList) => {
	const newMenuList = JSON.parse(JSON.stringify(menuList));

	return newMenuList.filter((item) => {
		item.children?.length && (item.children = getMenuList(item.children));
		return !item.meta?.isHide;
	});
};
